from urllib.parse import quote_plus
from pymongo import MongoClient
from pymongo.errors import OperationFailure
from bson.son import SON
import pandas as pd

def get_database_info():
    #数据表定义
    columns = ['Database', 'Collection', 'Document Count', 'Collection Size (bytes)']
    df = pd.DataFrame(columns=columns)

    # MongoDB 连接信息
    mongo_host = 'xxxxx'
    mongo_port = 8030
    mongo_user = 'xxx'
    mongo_password = 'xxx'
    escaped_password = quote_plus(mongo_password)
    escaped_host = quote_plus(mongo_host)

    # 连接 MongoDB
    connection_string = f'mongodb://{mongo_user}:{escaped_password}@{escaped_host}:{mongo_port}/admin'
    client = MongoClient(connection_string)
    # 获取所有数据库列表
    databases = client.list_database_names()


    # 遍历每个数据库
    for db_name in databases:
        #db = "statistic"
        db = client[db_name]
        # 获取数据库中所有集合
        collections = db.list_collection_names()
        # 遍历每个集合
        for collection_name in collections:
            try:
                collection = db[collection_name]
                # 获取文档数
                document_count = collection.count_documents({})
                # 获取集合大小
                collection_size = collection.estimated_document_count()
                print(f"Database: {db_name}, Collection: {collection_name}")
                print(f"Document Count: {document_count}")
                print(f"Collection Size: {collection_size} bytes\n")
                df = df.append({'Database': db_name, 'Collection': collection_name, 'Document Count': document_count,'Collection Size (bytes)': collection_size}, ignore_index=True)
            except OperationFailure as op_err:
                    # 忽略特定的 OperationFailure 异常
                    if 'system.keys' in str(op_err):
                        print(f"Ignoring OperationFailure for collection {collection_name}")
                    else:
                        # 处理其他 OperationFailure 异常
                        print(f"OperationFailure for collection {collection_name}: {op_err}")
        # 保存DataFrame 到CSV中
        df.to_csv('xuanyun-tyy.csv', index=False)

if __name__ == "__main__":
    get_database_info()